package main

import (
	"fmt"
	"zinx/mmo_game_zinx/apis"
	"zinx/mmo_game_zinx/core"
	"zinx/ziface"
	"zinx/znet"
)

// OnConnectionAdd 创建连接之后的HOOK函数
func OnConnectionAdd(conn ziface.IConnection) {
	//创建一个player对象
	player := core.NewPlayer(conn)
	//给客户端发送msgID=1的消息(同步playerID)
	player.SyncPid()
	//给客户端发送msgID=200的消息(广播position)
	player.BroadCastStartPosition()
	//将当前玩家添加到世界管理模块中
	core.WorldManagerObj.AddPlayer(player)
	//为当前连接绑定一个属性信息
	conn.SetProperty("pid", player.Pid)
	fmt.Println("======>Player ID = ", player.Pid, " is online!")
}

// OnConnectionDelete 创建连接之后的HOOK函数
func OnConnectionDelete(conn ziface.IConnection) {
	pid, err := conn.GetProperty("pid")
	if err != nil {
		fmt.Println("Get Property err!")
		return
	}
	player := core.WorldManagerObj.GetPlayerByPid(pid.(int32))
	//触发下线业务
	player.OffLine()
	fmt.Println("====>Player pid = ", pid, " offline...")
}

func main() {
	//创建Zinx Server句柄
	s := znet.NewServer("MMO GAME Zinx")
	//创建建立连接之后、销毁连接之前的HOOK函数
	s.SetOnConnCreate(OnConnectionAdd)
	s.SetOnConnDestroy(OnConnectionDelete)
	//自定义添加路由
	s.AddRouter(2, &apis.WorldChatAPI{})
	s.AddRouter(3, &apis.MoveApi{})
	//启动Server
	s.Serve()
}
